/* eslint-disable @typescript-eslint/camelcase */
/**
 * Created by zhangsong on 2019-05-22.
 */
import moment from 'moment';
import { datetimeFormat, WorkCardDefault } from '@/constants/styleConfig';
import {
  requestPostByToken,
  requestGetByToken,
  requestPutByToken,
  requestDeleteByToken,
} from '@/utils/request';
import URI from '@/services/uri';
import globalConfig from '@/constants/config';

const url = URI.application;

const setDataModify = list => {
  let arr = [];
  arr = Array.isArray(list)
    ? list.map((item, index) => {
      item.url = `${globalConfig.host}${globalConfig.baseAPI}${item.url}`;
      item.name = item.url.substring(item.url.lastIndexOf('/') + 1);
      item.uid = (index + 1) * -1;
      item.status = 'done';
      return item;
    })
    : []
  return arr;
}

const setDataList = list => {
  let annexesBase64 = [];
  if (Array.isArray(list)) {
    annexesBase64 = list.map(item => item.url || item.thumbUrl);
  }

  return annexesBase64
}

const setNewDataList = list => {
  let annexesBase64 = [];
  if (Array.isArray(list)) {
    annexesBase64 = list.map(item => item.thumbUrl);
  }

  return annexesBase64
}

export const registerEface = params =>
  requestPostByToken({
    url: url.person.registerEface,
    body: params,
  });

export const registerEfaceIc = data =>
  requestPutByToken({
    url: url.person.registerEfaceIc.replace('{id}', data.staffId),
    body: { icCard: data.icCard },
  });

// 强制将记录更新为登记成功
export const forceRegisterSuccess = id =>
  requestPutByToken({
    url: url.person.forceUpdateSuccess,
    body: {
      staffId: id,
    },
  });

// 更新註銷日期
export const updateCallDate = async param => {
  const response = await requestPostByToken({
    url: url.staffUrl.modifyacll,
    body: param,
  });
  return response;
}

// 获取group list
export const getGroupList = async () => {
  const response = await requestPostByToken({
    url: URI.common.getgrouplist,
    body: {},
  });
  return response;
}


// 新增group list
export const creatGroupList = async param => {
  const response = await requestPostByToken({
    url: URI.common.creatgrouplist,
    body: param,
  });
  return response;
}

/**
 * 审核通过
 * @param id
 */
export const approval = id =>
  requestGetByToken({
    url: url.staffUrl.approval.replace('{id}', id),
  });

// 审核不通过
export const disapproval = id =>
  requestGetByToken({
    url: url.staffUrl.disapproval.replace('{id}', id),
  });

export const reviewokstaff = id =>
  requestGetByToken({
    url: url.staffUrl.reviewok.replace('{id}', id),
  });

export const getPDFById = id =>
  requestGetByToken({
    url: url.staffUrl.pdf.replace('{id}', id),
  });

// 下载报表
export const staffDownXlsx = () =>
  requestGetByToken({
    url: url.staffUrl.downxlsx,
  });

export const listByParam = async query => {
  const {
    drivingLicense,
    fileGroupId,
    idCardNo,
    needDriving,
    otherName,
    passNumber,
    staffNo,
    zoneSpecified,
    ...other
  } = query;

  const { data, page, page_size: pageSize, total } = await requestGetByToken({
    url: url.staffUrl.newlist,
    query: {
      ...other,
      driving_license: drivingLicense,
      file_group_id: fileGroupId,
      idcard_no: idCardNo,
      need_driving: needDriving,
      other_names: otherName,
      pass_numbered: passNumber,
      staff_no: staffNo,
      specified_zone: zoneSpecified,
    },
  });
  const rows = data.map(item => ({
    ...item,
    alias: item.alias,
    createTime: item.create_time,
    updateTime: item.update_time,
    department: item.department,
    division: item.division,
    drivingLicense: item.driving_license,
    fileGroupId: item.file_group_id,
    id: item.id,
    idCardNo: item.idcard_no,
    needDriving: item.need_driving,
    otherName: item.other_names,
    passNumber: item.pass_numbered,
    position: item.position,
    reasons: item.reasons,
    staffNo: item.staff_no,
    surname: item.surname,
    zoneSpecified: item.zone_specified,
    expiredDate: item.expire_date,
    efaceStatus: item.eface_status,
    headPhoto: `${globalConfig.host}${globalConfig.baseAPI}${item.photograph_url}`,

  }));
  return {
    data: rows,
    page,
    pageSize,
    total,
  };
};

export const getById = async id => {
  const data = await requestGetByToken({
    url: url.staffUrl.getById.replace('{id}', id),
  });
  const result = {
    ...data,
    createTime: data.create_time,
    updateTime: data.update_time,
    staffVehicle: data.staff_vehicle,
    drivingLicenseExpire: data.driving_license_expire,
    cardBack: data.card_back,
    cardFront: data.card_front,
    cardNo: data.card_no,
    cardGroupId: data.card_group_id,
    fileGroupId: data.file_group_id,
    surname: data.surname,
    otherName: data.other_names,
    alias: data.alias,
    idCardNo: data.idcard_no,
    staffNo: data.staff_no,
    position: data.position,
    division: data.division,
    department: data.department,
    passNumber: data.pass_numbered,
    reasons: data.reasons,
    checkedApproved: data.checked_approved,
    expiredDate: data.expire_date,
    efaceStatus: data.eface_status,
    projectExpire: data.project_expire,

    // TODO: 下面两个字段没处理
    needDriving: data.need_driving,
    drivingLicense: data.driving_license,

    id: data.id,
    zoneSpecified: Array.isArray(data.zone_list) ? data.zone_list.map(i => i.id) : [],
    zoneRequired: Array.isArray(data.zone_required_list)
      ? data.zone_required_list.map(i => i.id)
      : [],
    // 头像
    headPhoto: data.photograph_url
      ? [
        {
          id: -1,
          key: -1,
          uid: -1,
          status: 'done',
          url: `${globalConfig.host}${globalConfig.baseAPI}${data.photograph_url}`,
        },
      ]
      : [],
    annexes: setDataModify(data.annex_list),
    id_base64: setDataModify(data.id_paths),
    green_base64: setDataModify(data.green_paths),
    drive_base64: setDataModify(data.drive_paths),
    regist_base64: setDataModify(data.regist_paths),
    vacc_base64: setDataModify(data.vacc_paths),
    exemption_base64: setDataModify(data.exemption_paths),
    workerCardName1: WorkCardDefault.greenCard,
    workerCardName2: WorkCardDefault.registerCard,
    workerCardName3: WorkCardDefault.blueCard,
  };
  if (Array.isArray(data.card_list)) {
    data.card_list.forEach(i => {
      if (i.name === WorkCardDefault.greenCard) {
        result.workerCardName1 = i.name;
        result.workerCardExpiredDate1 = i.expire_date;
        result.workerCardNo1 = i.card_no;
      } else if (i.name === WorkCardDefault.registerCard) {
        result.workerCardName2 = i.name;
        result.workerCardExpiredDate2 = i.expire_date;
        result.workerCardNo2 = i.card_no;
        result.workerCardWorkType2 = i.worker_type_id;
      } else if (i.name === WorkCardDefault.blueCard) {
        result.workerCardName3 = i.name;
        result.workerCardExpiredDate3 = i.expire_date;
        result.workerCardNo3 = i.card_no;
      } else if (result.workerCardNo4) {
        // 如果第四张卡已经存在数据,将值赋值给第五张卡
        result.workerCardName5 = i.name;
        result.workerCardExpiredDate5 = i.expire_date;
        result.workerCardNo5 = i.card_no;
      } else {
        // 默认赋值给第四张卡
        result.workerCardName4 = i.name;
        result.workerCardExpiredDate4 = i.expire_date;
        result.workerCardNo4 = i.card_no;
      }
    });
    if (Array.isArray(data.listName)) {
      let newList = '';
      data.listName.forEach((i, k) => {
        if (k < data.listName.length - 1) {
          newList += `${i}, `
        } else {
          newList += `${i}`
        }
      })
      const list = data.listName.map(i => ({ value: i, label: i }))
      result.listName = list
      result.newlistName = newList;
    }
  }
  return result;
};

export const saveStaff = data => {
  const {
    drivingLicenseExpire,
    staffVehicle,
    cardNo,
    headPhoto,
    annexes,
    zoneRequired,
    zoneSpecified,

    surname,
    otherName,
    alias,
    idCardNo,
    staffNo,
    position,
    division,
    department,
    reasons,
    passNumber,
    checkedApproved,
    expiredDate,
    needDriving,
    workerCardName1,
    workerCardNo1,
    workerCardExpiredDate1,
    workerCardName2,
    workerCardNo2,
    workerCardExpiredDate2,
    workerCardWorkType2,
    workerCardName3,
    workerCardNo3,
    workerCardExpiredDate3,
    workerCardName4,
    workerCardNo4,
    workerCardExpiredDate4,
    workerCardName5,
    workerCardNo5,
    workerCardExpiredDate5,
    isBlack,
    groupName,
    isInfected,
    email,
    projectExpire,
    id_base64,
    green_base64,
    drive_base64,
    regist_base64,
    vacc_base64,
    exemption_base64,
    ...other
  } = data;
  const inspectionDate = data.inspection_exemption_time;
  const cardArr = [
    {
      name: workerCardName1,
      card_no: workerCardNo1,
      expire_date: workerCardExpiredDate1
        ? moment(workerCardExpiredDate1).format(datetimeFormat.date)
        : null,
    },
    {
      name: workerCardName2,
      card_no: workerCardNo2,
      expire_date: workerCardExpiredDate2
        ? moment(workerCardExpiredDate2).format(datetimeFormat.date)
        : null,
      worker_type_id: workerCardWorkType2,
    },
  ];
  if (workerCardNo3) {
    cardArr.push({
      name: workerCardName3,
      card_no: workerCardNo3,
      expire_date: workerCardExpiredDate3
        ? moment(workerCardExpiredDate3).format(datetimeFormat.date)
        : null,
    });
  }
  if (workerCardNo4) {
    cardArr.push({
      name: workerCardName4,
      card_no: workerCardNo4,
      expire_date: workerCardExpiredDate4
        ? moment(workerCardExpiredDate4).format(datetimeFormat.date)
        : null,
    });
  }
  if (workerCardNo5) {
    cardArr.push({
      name: workerCardName5,
      card_no: workerCardNo5,
      expire_date: workerCardExpiredDate5
        ? moment(workerCardExpiredDate5).format(datetimeFormat.date)
        : null,
    });
  }
  // 处理图片
  let headPhotoBase64 = null;
  if (Array.isArray(headPhoto) && headPhoto.length > 0) {
    headPhotoBase64 = headPhoto[0].thumbUrl;
  }
  let annexesBase64 = [];
  if (Array.isArray(annexes)) {
    annexesBase64 = annexes.map(item => item.thumbUrl);
  }
  let listName = null;
  if (Array.isArray(groupName)) {
    listName = groupName.map(i => `${i.value}`)
  }
  const body = {
    ...other,
    email,
    staff_vehicle: staffVehicle,
    driving_license_expire: drivingLicenseExpire
      ? moment(drivingLicenseExpire).format(datetimeFormat.date)
      : null,
    card_no: cardNo,
    head_photo: headPhotoBase64,
    annexes: annexesBase64,
    id_base64: setNewDataList(id_base64),
    green_base64: setNewDataList(green_base64),
    drive_base64: setNewDataList(drive_base64),
    regist_base64: setNewDataList(regist_base64),
    vacc_base64: setNewDataList(vacc_base64),
    exemption_base64: setNewDataList(exemption_base64),
    surname,
    other_names: otherName,
    alias,
    idcard_no: idCardNo,
    staff_no: staffNo,
    position,
    division,
    department,
    zone_required_list: zoneRequired,
    need_driving: needDriving,
    zone_list: zoneSpecified,
    pass_numbered: passNumber,
    checked_approved: checkedApproved,
    expire_date: expiredDate ? moment(expiredDate).format(datetimeFormat.date) : null,
    project_expire: projectExpire ? moment(projectExpire).format(datetimeFormat.date) : null,
    reasons,
    card_list: cardArr,
    isBlack: isBlack ? 2 : 1,
    listName,
    inspection_exemption_time: inspectionDate
      ? moment(inspectionDate).format(datetimeFormat.date)
      : null,
    isInfected: isInfected ? 2 : 1,
  };
  return requestPostByToken({
    url: url.staffUrl.save,
    body,
  });
};

export const removeById = id =>
  requestDeleteByToken({
    url: url.staffUrl.removeById.replace('{id}', id),
  });

export const updateById = ({ id, body }) => {
  const {
    staffVehicle,
    drivingLicenseExpire,
    cardBack,
    cardFront,
    // cardNo,
    newcardNo,
    cardGroupId,
    fileGroupId,
    headPhoto,
    annexes,
    zoneRequired,
    zoneSpecified,

    surname,
    otherName,
    alias,
    idCardNo,
    staffNo,
    position,
    division,
    department,
    reasons,
    passNumber,
    needDriving,
    checkedApproved,
    expiredDate,
    workerCardName1,
    workerCardNo1,
    workerCardExpiredDate1,
    workerCardName2,
    workerCardNo2,
    workerCardExpiredDate2,
    workerCardWorkType2,
    workerCardName3,
    workerCardNo3,
    workerCardExpiredDate3,
    workerCardName4,
    workerCardNo4,
    workerCardExpiredDate4,
    workerCardName5,
    workerCardNo5,
    workerCardExpiredDate5,
    isBlack,
    groupName,
    isInfected,
    email,
    projectExpire,
    id_base64,
    green_base64,
    drive_base64,
    regist_base64,
    vacc_base64,
    exemption_base64,
    ...other
  } = body;
  const inspectionDate = body.inspection_exemption_time;
  const cardArr = [
    {
      name: workerCardName1,
      card_no: workerCardNo1,
      expire_date: workerCardExpiredDate1
        ? moment(workerCardExpiredDate1).format(datetimeFormat.date)
        : null,
    },
    {
      name: workerCardName2,
      card_no: workerCardNo2,
      expire_date: workerCardExpiredDate2
        ? moment(workerCardExpiredDate2).format(datetimeFormat.date)
        : null,
      worker_type_id: workerCardWorkType2,
    },
  ];
  if (workerCardNo3) {
    cardArr.push({
      name: workerCardName3,
      card_no: workerCardNo3,
      expire_date: workerCardExpiredDate3
        ? moment(workerCardExpiredDate3).format(datetimeFormat.date)
        : null,
    });
  }
  if (workerCardNo4) {
    cardArr.push({
      name: workerCardName4,
      card_no: workerCardNo4,
      expire_date: workerCardExpiredDate4
        ? moment(workerCardExpiredDate4).format(datetimeFormat.date)
        : null,
    });
  }
  if (workerCardNo5) {
    cardArr.push({
      name: workerCardName5,
      card_no: workerCardNo5,
      expire_date: workerCardExpiredDate5
        ? moment(workerCardExpiredDate5).format(datetimeFormat.date)
        : null,
    });
  }
  // 处理图片
  let headPhotoBase64 = null;
  if (Array.isArray(headPhoto) && headPhoto.length > 0) {
    headPhotoBase64 = headPhoto[0].url || headPhoto[0].thumbUrl;
  }
  let annexesBase64 = [];
  if (Array.isArray(annexes)) {
    annexesBase64 = annexes.map(item => item.url || item.thumbUrl);
  }
  let listName = null;
  if (Array.isArray(groupName)) {
    listName = groupName.map(i => `${i.value}`)
  }
  const params = {
    ...other,
    driving_license_expire: drivingLicenseExpire
      ? moment(drivingLicenseExpire).format(datetimeFormat.date)
      : null,
    staff_vehicle: staffVehicle,
    card_back: cardBack,
    card_front: cardFront,
    card_no: newcardNo,
    file_group_id: fileGroupId,
    card_group_id: cardGroupId,
    head_photo: headPhotoBase64,
    annexes: annexesBase64,
    id_base64: setDataList(id_base64),
    green_base64: setDataList(green_base64),
    drive_base64: setDataList(drive_base64),
    regist_base64: setDataList(regist_base64),
    vacc_base64: setDataList(vacc_base64),
    exemption_base64: setDataList(exemption_base64),
    surname,
    other_names: otherName,
    alias,
    idcard_no: idCardNo,
    staff_no: staffNo,
    position,
    division,
    department,
    zone_required_list: zoneRequired,
    need_driving: needDriving,
    zone_list: zoneSpecified,
    pass_numbered: passNumber,
    checked_approved: checkedApproved,
    expire_date: expiredDate ? moment(expiredDate).format(datetimeFormat.date) : null,
    project_expire: projectExpire ? moment(projectExpire).format(datetimeFormat.date) : null,
    reasons,
    card_list: cardArr,
    isBlack: isBlack ? 2 : 1,
    listName,
    email,
    inspection_exemption_time: inspectionDate
      ? moment(inspectionDate).format(datetimeFormat.date)
      : null,
    isInfected: isInfected ? 2 : 1,
  };
  console.log('我做了吗', params)
  return requestPutByToken({
    url: url.staffUrl.modifyById.replace('{id}', id),
    body: params,
  });
};
